WintergraspFu = AceLibrary("AceAddon-2.0"):new("FuBarPlugin-2.0", "AceDB-2.0", "AceEvent-2.0")
WintergraspFu:RegisterDB("WintergraspFuDB");
local L = AceLibrary("AceLocale-2.2"):new("WintergraspFu")

WintergraspFu.title = "WintergraspFu "..GetAddOnMetadata("Fubar_WintergraspFu", "Version") 
WintergraspFu.hasIcon = "Interface\\Icons\\INV_Jewelry_Ring_66"
WintergraspFu.defaultPosition = "LEFT"
WintergraspFu.cannotDetachTooltip = true
WintergraspFu.canHideText = false
WintergraspFu.hasNoColor = true
WintergraspFu.cannotAttachToMinimap = true

--
-- Startup, enabling and disabling
--
function WintergraspFu:OnEnable() -- AceAddon-2.0 event
	self:ScheduleRepeatingEvent(self.UpdateText, 1, self)
end

--
-- Periodic updates of text
--
function WintergraspFu:EverySecond() -- AceEvent-2.0 event
	self:UpdateText()
end

--
-- Update FuBar menu item with time to match
--
function WintergraspFu:OnTextUpdate() -- FuBarPlugin-2.0 event
	local seconds = GetWintergraspWaitTime() or 0 -- sanity check to avoid nil
	self:SerializeDB(seconds)
	local timeText = self:GetTimeText(seconds)
	if self:IsTextColored() then
		self:SetText("|cffffffff"..L["WG"]..":|r |cffffff00" .. timeText .. "|r")
	else
		self:SetText(L["WG"]..": " .. timeText)
	end
end

--
-- let AceDB-2.0 serialize our results so external parsers can access them
--
function WintergraspFu:SerializeDB(seconds)
	local timestamp = time()
	self.db.realm.lastsync = timestamp -- system timestamp in seconds
	self.db.realm.nextbattle = timestamp + seconds
end

--
-- Return Wintergasp wait time in "h:m:s*", or "active" if match in progress
-- *Seconds are only returned during the final minute
--
function WintergraspFu:GetTimeText(seconds)
	local timeText = ""
	if seconds == 0 then
		timeText = L["Active"] -- match in progress
	else
		local h = math.floor(seconds / 3600)
		local m = math.floor(seconds % 3600 / 60)
		local s = seconds % 60
		if h > 0 then
			timeText = timeText .. h .. L["h"].." "
		end
		if m > 0 then
			timeText = timeText .. m .. L["m"].." "
		end
		-- only show seconds in last minute
		if h == 0 and m == 0 and s > 0 then
			timeText = timeText .. s .. L["s"]
		end
	end
	return timeText
end